//
//  UIColor+JCHex.m
//  JCPublicKit-Objc
//
//  Created by JasonLee on 2020/4/24.
//

#import "UIColor+JCHex.h"

@implementation UIColor (JCHex)

+ (UIColor * _Nonnull)jc_colorWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue {
    return [UIColor jc_colorWithRed:red green:green blue:blue alpha:1];
}
+ (UIColor * _Nonnull)jc_colorWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha {
    return [UIColor colorWithRed:red / 255.0 green:green / 255.0 blue:blue / 255.0 alpha:alpha];
}

+ (UIColor * _Nonnull)jc_colorWithHexString:(NSString * _Nonnull)hex {
    return [UIColor jc_colorWithHexString:hex alpha:1];
}
+ (UIColor * _Nonnull)jc_colorWithHexString:(NSString * _Nonnull)hex alpha:(CGFloat)alpha {
    NSString *cString = [[hex stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    if ([cString hasPrefix:@"0x"] || [cString hasPrefix:@"0X"]) {
        cString = [cString substringFromIndex:2];
    }
    
    if ([cString hasPrefix:@"#"]) {
        cString = [cString substringFromIndex:1];
    }
    
    if ([cString length] != 6) {
        return [UIColor clearColor];
    }
    
    NSRange range;
    range.length = 2;
    
    range.location = 0;
    NSString *rString = [cString substringWithRange:range];
    
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    unsigned int red, green, blue;
    [[NSScanner scannerWithString:rString] scanHexInt:&red];
    [[NSScanner scannerWithString:gString] scanHexInt:&green];
    [[NSScanner scannerWithString:bString] scanHexInt:&blue];
    
    return [UIColor jc_colorWithRed:red green:green blue:blue alpha:alpha];
}

+ (UIColor * _Nonnull)jc_colorWithHexValue:(NSUInteger)hex {
    return [UIColor jc_colorWithHexValue:hex alpha:1];
}
+ (UIColor * _Nonnull)jc_colorWithHexValue:(NSUInteger)hex alpha:(CGFloat)alpha {
    CGFloat red = ((hex & 0xFF0000) >> 16);
    CGFloat green = ((hex & 0xFF00) >> 8);
    CGFloat blue = (hex & 0xFF);
    
    return [UIColor jc_colorWithRed:red green:green blue:blue alpha:alpha];
}

+ (UIColor * _Nonnull)jc_colorByRandom {
    CGFloat red = (CGFloat)(arc4random_uniform(255) + 0) / 255.0;
    CGFloat green = (CGFloat)(arc4random_uniform(255) + 0) / 255.0;
    CGFloat blue = (CGFloat)(arc4random_uniform(255) + 0) / 255.0;
    return [UIColor jc_colorWithRed:red green:green blue:blue alpha:1];
}

@end
